﻿using System.Linq.Expressions;
using Basic.FormDAL;
using Basic.FormModel.DB;
using Basic.FormRemoteModel.PhyFormInter.Model;
using WeDonekRpc.Helper;

namespace Basic.FormCollect.lmpl
{
    internal class PhysicalTableCollect : IPhysicalTableCollect
    {
        private readonly IPhysicalTableDAL _BasicDAL;

        public PhysicalTableCollect ( IPhysicalTableDAL basicDAL )
        {
            this._BasicDAL = basicDAL;
        }

        public void Sync ( long formId, PhyFormTable[] table )
        {
            if ( table.IsNull() )
            {
                if ( this._BasicDAL.IsExists(c => c.FormId == formId) )
                {
                    this._BasicDAL.Clear(formId);
                }
            }
            else if ( this._BasicDAL.IsExists(c => c.FormId == formId) )
            {
                this._BasicDAL.Set(formId, table);
            }
            else
            {
                this._BasicDAL.Add(formId, table);
            }
        }
        public void Clear ( long formId )
        {
            long[] ids = this._BasicDAL.Gets(a => a.FormId == formId, a => a.Id);
            if ( ids.IsNull() )
            {
                return;
            }
            this._BasicDAL.Delete(ids);
        }
        public Result[] GetsByFormId<Result> ( long formId ) where Result : class, new()
        {
            return this._BasicDAL.Gets<Result>(a => a.FormId == formId);
        }
        public Result[] Gets<Result> ( long[] tableId ) where Result : class, new()
        {
            return this._BasicDAL.Gets<Result>(tableId);
        }

        public Result Get<Result> ( long id ) where Result : class, new()
        {
            return this._BasicDAL.Get<Result>(id);
        }
        public Result[] GetsByFormId<Result> ( long formId, Expression<Func<DBPhysicalTable, Result>> selector ) where Result : class, new()
        {
            return this._BasicDAL.Gets(a => a.FormId == formId, selector);
        }

        public bool CheckIsNull ( long formId )
        {
            return this._BasicDAL.IsExists(c => c.FormId == formId) == false;
        }
    }
}
